package com.xuhj.controller;

import com.xuhj.pojo.Dept;
import com.xuhj.service.DeptClientService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@RestController
public class DeptConsumerController {

    // 消费者中不应该有service

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private DeptClientService deptClientService;

    @Autowired
    private DiscoveryClient client;
    /**
     * 非负载均衡所配置的请求
     * private static final String REST_URL_PREFIX = "http://localhost:8001";
     */

    /**
     * 通过ribbon，负载均衡的地址,服务的地址 IRule接口配置负载均衡的规则，默认轮询访问
     * 测试地址：http://localhost:80/consumer/dept/get
     * private static final String REST_URL_PREFIX = "http://SPRINGCLOUD-PROVIDER-DEPT";
     */
    @GetMapping("/consumer/dept/get/{id}")
    public Dept getDeptByRest(@PathVariable("id") Long id) {
        /**
         * getForObject
         * @param1 URL
         * @param2 返回值类型
         */
//        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/get/" + id, Dept.class);
        return this.deptClientService.queryById(id);
    }

    /**
     * produces等等属性该声明的都手动声明一下，避免出现各种问题
     */
    @PostMapping(value = "/consumer/dept/add", produces = "application/json;charset=UTF-8")
    public Boolean addDeptByRest(Dept dept) {
//        return restTemplate.postForObject(REST_URL_PREFIX + "/dept/add", dept, Boolean.class);
        return this.deptClientService.addDept(dept);
    }

    @GetMapping("/consumer/dept/get")
    public List<Dept> getAllDeptByRest() {
//        return restTemplate.getForObject(REST_URL_PREFIX + "/dept/list", List.class);
        return deptClientService.queryAll();
    }


    /**
     * 获取微服务的一些信息,服务联调用
     */
    @RequestMapping("/consumer/dept/discovery")
    public Object discovery() {
        List<String> services = client.getServices();
        System.out.println("discovery => services:" + services);
        List<ServiceInstance> instances = client.getInstances("SPRINGCLOUD-PROVIDER-DEPT_8001");
        for (ServiceInstance instance : instances) {
            System.out.println(instance.getHost() + "\t" +
                    instance.getPort() + "\t" +
                    instance.getUri() + "\t" +
                    instance.getInstanceId() + "\t" +
                    instance.getServiceId() + "\t" +
                    instance.getMetadata());
        }
        return this.client;
    }
}
